<template>
  <div class="ts-img-upload">
    <!-- 详情页不可编辑   在详情页面 如果没有照片 则显示无照片-->
    <!--    <div v-if="fileList.length === 0 && isMobile && inputDisabled">无照片</div>-->
    <el-upload
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :limit="limit"
      accept="image/*"
      :class="{
        hide: this.fileList.length >= this.limit,
        'is-disabled': inputDisabled,
      }"
      :before-upload="onBeforeUpload"
      :on-remove="onRemove"
      :before-remove="beforeRemove"
      :on-error="onUploadError"
      :on-exceed="onExceed"
      :on-preview="onPictureCardPreview"
      :on-success="onUploadSuccess"
      :http-request="onHttpRequest"
    >
      <i :class="addIconClass"></i>
      <!--      <div-->
      <!--        slot="file"-->
      <!--        slot-scope="{ file }"-->
      <!--        style="width: 100%; height: 100%; position: relative"-->
      <!--      >-->
      <!--        <img-->
      <!--          class="el-upload-list__item-thumbnail"-->
      <!--          :src="file.url"-->
      <!--          alt=""-->
      <!--          @click="onPictureCardPreview(file)"-->
      <!--        />-->
      <!--      </div>-->
    </el-upload>
    <div class="el-upload__tip" slot="tip" v-if="showTip && !inputDisabled">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>
    <!--在pc上的预览-->
    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="40%"
      append-to-body
    >
      <img :src="dialogImageUrl" class="preview_pic" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script lang="jsx">
import { uploadFile, getFileUrl } from "../../api/index.js";
import { showError, showLoading, clearLoading } from "../../utils/message.js";
export default {
  name: "TsImgUpload",
  props: {
    value: {
      type: [String, Object, Array],
      // default: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
    },
    limit: Number,
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    addIconClass: {
      type: String,
      default: "el-icon-plus",
    },
    imgerror: [String, Object],
    disabled: Boolean,
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      fileList: [],
      exceedMaxMemory: false
    };
  },
  inject: {
    isFormGenerator: {
      type: Boolean,
      default: false,
    },
    elForm: {
      default: "",
    },
    conf: {
      type: Object,
      default: {
        __config__: {},
      },
    },
  },
  watch: {
    "fileList.length"(val) {
      this.updateValue()
    },
    value: {
      async handler(val) {
        // console.log("val", val);
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : []
          // 然后将数组转为对象数组
          let l = list.map((row)=>{
            return row.url ? new Promise(resolve=>resolve(row.url)) : getFileUrl(row)
          })
          let urlList = await Promise.all(l)
          urlList.forEach((url, i)=>{
            list[i].url = url
          })
          this.fileList = list
        } else {
          this.fileList = [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    inputDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {
  },
  mounted() {},
  methods: {
    onClick() {
    },
    updateValue(){
      let value = this.fileList.map((item) => {
        let o = {...item}
        delete o.url
        return o
      });
      this.$emit("input", value);
    },
    beforeRemove(file, fileList) {
      // return this.$confirm("确定移除该图片?");
      if (this.exceedMaxMemory) return;
      return this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
    },
    async onRemove(file, fileList) {
      console.log("onRemove", file, fileList);
      let index = this.fileList.findIndex((t) => t.uid === file.uid);
      if (index > -1) {
        //   await this.$confirm("确认删除?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   });
        this.fileList.splice(index, 1);
        this.updateValue()
      }
    },
    async onHttpRequest({ file }){
      try {
        console.log("file", file);
        showLoading();
        let res = await uploadFile(file);
        this.onUploadSuccess(res);
      } catch (error) {
        console.error(error);
        showError("上传失败");
      }
    },
    // 上传成功回调
    async onUploadSuccess(res) {
      // console.log("res", res);
      let { data } = res;
      const row = data[0]
      let url = await getFileUrl(row)
      row.url = url
      this.fileList.push(row);
      clearLoading();
      this.updateValue()
    },
    // 上传前loading加载
    onBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        if (file.type) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          isImg = this.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
        } else {
          // 某些手机获取不到file.type
          isImg = true;
        }
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        showError(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          showError(`上传图片大小不能超过 ${this.fileSize} MB!`);
          this.exceedMaxMemory = true;
          return false;
        } else {
          this.exceedMaxMemory = false;
        }
      }
      showLoading();
    },
    // 上传失败
    onUploadError() {
      showError("上传失败");
      clearLoading();
    },
    // 文件个数超出
    onExceed() {
      showError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 预览
    onPictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card,
::v-deep.is-disabled .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}

::v-deep .el-upload--picture-card {
  margin: 0 8px 8px 0;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  //overflow: visible;
}

.ts-img-upload > div {
  display: flex;
  flex-direction: column-reverse;
  justify-content: flex-end;
}
.el-upload__tip {
  flex-direction: row !important;
  justify-content: flex-start !important;
}
</style>
<style lang="scss">
.ts-img-upload {
  .el-icon-circle-close {
    font-size: 18px;
    position: absolute;
    top: -10px;
    right: -10px;
    background: #fff;
  }
  .el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
}
.is-mobile {
  .ts-img-upload {
    .el-upload-list--picture-card .el-upload-list__item,
    .el-upload--picture-card {
      width: 65px;
      height: 65px;
    }
    .el-upload--picture-card {
      line-height: 76px;
    }
    .el-icon-circle-close {
      font-size: 14px;
      top: -6px;
      right: -8px;
    }
    .preview_cont {
      width: 100vw;
      height: 100vh;
      top: 0;
      left: 0;
      z-index: 200;
      position: fixed;
      background: rgba(54, 50, 50, 0.5);
      .preview_pic {
        width: 100vw;
        max-height: 75vh;
        margin: auto 0;
      }
    }
  }
}
</style>
